import { find, instantiate, Node, Prefab, resources } from "cc"

export const DialogDef = {
    UISKILL: 'UISKill',
    UISETTING: 'UISetting'
}

export class UIManager {
    private static _instance: UIManager = null

    private uiRoot: Node = null
    private panels: Map<string, Node> = new Map()

    public static get instance(): UIManager {
        if (this._instance === null) {
            this._instance = new UIManager()
        }
        return this._instance
    }

    public openPanel(name: string, setIndex: boolean = true) {
        if (this.uiRoot === null) this.uiRoot = find('UIRoot')

        if (this.panels.has(name)) {
            const panel = this.panels.get(name)
            panel.active = true
            if (setIndex) {
                const index = this.uiRoot.children.length - 1
                panel.setSiblingIndex(index)
            }

            return
        }

        resources.load(`/ui/prefab/${name}`, Prefab, (err: Error, prefab: Prefab) => {
            const panel = instantiate(prefab)
            this.uiRoot.addChild(panel)
            this.panels.set(name, panel)

            if (setIndex) {
                const index = this.uiRoot.children.length - 1
                panel.setSiblingIndex(index)
            }
        })
    }

    public closePanel(name: string, destory: boolean = false) {
        const panel = this.panels.get(name)
        if (!panel) return

        if (destory) {
            // this.panels.delete(name)
            panel.removeFromParent()
            return
        }

        panel.active = false
    }

    public openDialog(name: string) {
        for (const key in DialogDef) {
            // DialogDef[key] === name ? this.openPanel(name) : this.closePanel( DialogDef[key])
            if (DialogDef[key] === name) this.openPanel(name)
        }
    }

    public closeDialog(destory?: boolean) {
        for (const key in DialogDef) {
            this.closePanel(DialogDef[key], destory)
        }
    }

    public clearAllPanels() {
        for (const panel of this.panels.values()) {
            panel.removeFromParent()
        }
        this.panels = new Map()
        this.uiRoot = null
    }


}